﻿/*
数据类型：时间，字符串，数值（包括整型和浮点型）
默认是字符串型
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CsvViewer
{
    public partial class MainForm : Form
    {
        CSV csv = new CSV();

        List<FilterCondition> conditions = new List<FilterCondition>();
        public MainForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            csv.Read("20240729.csv");
            // Console.WriteLine($"Rows X Columns: {csv.RowCount} X {csv.ColumnCount} ");

            DataImportForm dif = new DataImportForm();
            dif.SetData(csv);
            dif.ShowDialog();

            AttachDataToListView(ApplyFilter(csv, conditions));
        }


        private void button2_Click(object sender, EventArgs e)
        {
            if (lvMainView.Columns.Count == 0)
            {
                MessageBox.Show("Load first.");
                return;
            }

            FilterConfigForm fcf = new FilterConfigForm();
            fcf.conditions = conditions;
            fcf.ShowDialog();
            conditions = fcf.conditions;

            AttachDataToListView(ApplyFilter(csv, conditions));
        }

        private void AttachDataToListView(List<string[]> list)
        {
            lvMainView.Items.Clear();
            lvMainView.Columns.Clear();
            ConditionConfigControl.Fields.Clear();
            for (int i = 0; i < list[0].Length; i++)
            {
                var headerName = list[0][i];
                ColumnHeader columnHeader = new ColumnHeader() { Text = headerName, Width = 200 };
                lvMainView.Columns.Add(columnHeader);
                ConditionConfigControl.Fields.Add(headerName);
            }

            for (int row = 1; row < list.Count; row++)
            {
                ListViewItem lvItem = new ListViewItem(list[row][0]);
                for (int column = 1; column < csv.ColumnCount; column++)
                    lvItem.SubItems.Add(list[row][column]);
                lvMainView.Items.Add(lvItem);
            }
        }

        public List<string[]> ApplyFilter(CSV csv, List<FilterCondition> conditions)
        {
            List<string[]> result = new List<string[]>();
            string[] header = csv.GetRowAt();
            result.Add(header);
            for (int row = 1; row < csv.RowCount; row++)
            {
                var rowi = csv.GetRowAt(row);
                if (conditions.Count == 0 || FilterCondition.All(header, rowi, conditions))
                    result.Add(rowi);
            }

            return result;
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
        }
    }
}
